package cmd

import (
	"fmt"
	"github.com/shirou/gopsutil/process"
	"github.com/spf13/cobra"
	"io/ioutil"
	"os"
	"os/exec"
)

func init() {
	var daemon bool
	startCmd := &cobra.Command{
		Use:   "start",
		Short: "开始运行!",
		Long:  `启动程序,启动时可以添加-d参数代表后台启动`,
		Run: func(cmd *cobra.Command, args []string) {
			//strb, _ := ioutil.ReadFile("pid")
			// todo 目前没有做启动前的检查,启动前容易自己死循环,无法解决
			fileAll := os.Args[0]
			if daemon {
				// E:\Go\pfd\pfd.exe
				command := exec.Command(os.Args[0], "start")
				err := command.Start()
				if err == nil {
					fmt.Printf("开始后台启动 "+fileAll+" [PID] %d running...\n", command.Process.Pid)
					ioutil.WriteFile("pid", []byte(fmt.Sprintf("%d", command.Process.Pid)), 0666)
					daemon = false
					fmt.Println("后台运行....")
					os.Exit(0)
				} else {
					fmt.Println("运行错误!,", err)
				}
			} else {
				fmt.Println("前台运行")
				Run()
			}
		},
	}
	startCmd.Flags().BoolVarP(&daemon, "deamon", "d", false, "is daemon?")
	rootCmd.AddCommand(startCmd)
}
func ProcessName() map[int32]string {
	mp := make(map[int32]string)
	pids, _ := process.Pids()
	for _, pid := range pids {
		pn, _ := process.NewProcess(pid)
		pName, _ := pn.Name()
		mp[pid] = pName
		//fmt.Println(pid,pName)

	}
	return mp
}
